<template>
  <Card>
    <Alert v-if="openErrorAlert" show-icon type="error">审核不通过原因：{{ process.reason }}</Alert>
    <div id="putMaterial">
      <div class="title">
        <Icon size="18" type="md-list-box"/>
        物资入库
        <Divider/>
      </div>
      <div class="from">
        <Form ref="form" :label-width="170" :model="form" :rules="formValidate" inline>
          <div class="fromTitle">基础信息</div>
          <Row>
            <Col span="10">
            <Form-item label="入库时间：" prop="put_time">
              <DatePicker
                v-model="form.put_time"
                :editable="false"
                placeholder="选择时间"
                type="datetime"
              ></DatePicker>
            </Form-item>
            </Col>
            <Col span="10">
            <FormItem label="供应商：" prop="supplier">
              <Input v-model="form.supplier" placeholder @on-change="supplierChange"/>
            </FormItem>
            </Col>
          </Row>
          <Row>
            <Col span="10">
            <FormItem label="合计金额：">
              <Input v-model="form.total_money" placeholder readonly/>
            </FormItem>
            </Col>
          </Row>
          <div class="fromTitle">入库详情</div>
          <div class="btns">
            <!--
              :disabled="detailDisabled" -->
            <Button
              icon="ios-add"
              target="_self"
              type="primary"
              @click="toAdd"
            >添加
            </Button>
            <Button icon="md-remove" type="error" @click="delAll">删除</Button>
          </div>
          <div style="margin-bottom:15px">
            <Table
              ref="selection"
              :columns="columns"
              :data="dataStart"
              :loading="loading"
              border
              height="350"
              size="small"
              stripe
              @on-selection-change="showSelect($event, 'start')"
            >
              <template slot="action" slot-scope="{ row, index }">
                <a
                  class="edit"
                  size="small"
                  style="color:#2d8cf0;font-size: 12px;"
                  type="text"
                  @click="edit(row)"
                >编辑</a>
                <Divider type="vertical"/>
                <a class="del" style="color:#ed4014;font-size: 12px;" @click="del(row)">删除</a>
              </template>
            </Table>
          </div>
          <div style="height:50px;"></div>
          <div class="fromItem">
            <FormItem label>
              <Button
                :loading="submitLoading"
                icon="md-checkmark-circle"
                style="margin-right:10px"
                type="primary"
                @click="handleSubmit('form')"
              >保存
              </Button>
              <Button
                :loading="submitResetLoading"
                icon="md-checkmark-circle"
                style="margin-right:10px"
                type="primary"
                @click="handleSubmitReset"
              >保存并提交
              </Button>
              <Button icon="md-refresh" type="default" @click="handleReset">重置</Button>
            </FormItem>
          </div>
        </Form>
      </div>
      <Modal
        v-model="modal"
        :mask-closable="false"
        :styles="{top: '20px'}"
        title="添加物资详情"
        width="850"
        @on-cancel="cancel"
      >
        <Form ref="detailForm" :label-width="160" :model="detailForm" :rules="detailFormValidate">
          <Row>
            <Col span="12">
            <FormItem label="物资名称" prop="title">
              <Select
                v-model="detailForm.title"
                allow-create
                clearable
                filterable
                @on-create="addTitle"
                @on-change="changeMaterial"
                @on-clear="clearMaterial"
              >
                <Option
                  v-for="item in materialList"
                  :key="item.id"
                  :value="item.title"
                >{{ item.title }}
                </Option>
              </Select>
            </FormItem>
            </Col>
            <Col span="12">
            <FormItem label="规格" prop="specs">
              <Input v-model="detailForm.specs" placeholder></Input>
            </FormItem>
            </Col>
          </Row>
          <Row>
            <Col span="12">
            <FormItem label="单位" prop="unit">
              <Select v-model="detailForm.unit">
                <Option v-for="(item,index) in dict" :key="index" :value="index">{{ item }}</Option>
              </Select>
            </FormItem>
            </Col>
            <Col span="12">
            <FormItem label="数量" prop="amount">
              <Input v-model="detailForm.amount" placeholder></Input>
            </FormItem>
            </Col>
          </Row>
          <Row>
            <Col span="12">
            <FormItem label="单价" prop="price">
              <Input v-model="detailForm.price" placeholder></Input>
            </FormItem>
            </Col>
          </Row>
        </Form>
        <div slot="footer">
          <Button :loading="loading" @click="cancel('detailForm')">重置</Button>
          <Button
            :loading="submitLoading"
            style="margin-left:8px"
            type="primary"
            @click="submitF('detailForm')"
          >保存
          </Button>
        </div>
      </Modal>
      <Modal
        v-model="editModal"
        :mask-closable="false"
        :styles="{top: '20px'}"
        title="编辑物资详情"
        width="850"
        @on-cancel="cancel"
      >
        <Form
          ref="editDetailForm"
          :label-width="160"
          :model="editDetailForm"
          :rules="editDetailFormValidate"
        >
          <Row>
            <Col span="12">
            <FormItem label="物资名称" prop="title">
              <Select
                v-model="editDetailForm.title"
                allow-create
                clearable
                filterable
                @on-create="addTitle"
                @on-change="changeEditMaterial"
                @on-clear="clearEditMaterial"
              >
                <Option
                  v-for="item in materialList"
                  :key="item.id"
                  :value="item.title"
                >{{ item.title }}
                </Option>
              </Select>
            </FormItem>
            </Col>
            <Col span="12">
            <FormItem label="规格" prop="specs">
              <Input v-model="editDetailForm.specs" placeholder></Input>
            </FormItem>
            </Col>
          </Row>
          <Row>
            <Col span="12">
            <FormItem label="单位" prop="unit">
              <Select v-model="editDetailForm.unit">
                <Option v-for="(item,index) in dict" :key="index" :value="index">{{ item }}</Option>
              </Select>
            </FormItem>
            </Col>
            <Col span="12">
            <FormItem label="数量" prop="amount">
              <Input v-model="editDetailForm.amount" placeholder></Input>
            </FormItem>
            </Col>
          </Row>
          <Row>
            <Col span="12">
            <FormItem label="单价" prop="price">
              <Input v-model="editDetailForm.price" placeholder></Input>
            </FormItem>
            </Col>
          </Row>
        </Form>
        <div slot="footer">
          <Button :loading="loading" @click="cancel('editDetailForm')">重置</Button>
          <Button
            :loading="submitLoading"
            style="margin-left:8px"
            type="primary"
            @click="editSubmitF('editDetailForm')"
          >保存
          </Button>
        </div>
      </Modal>
    </div>
  </Card>
</template>
<script>
import './putMaterial.css'
import {
  editAddPutMaterialDetail,
  editDelPutMaterialDetail,
  editMaterial,
  editMaterialDetail,
  materialListSelect,
  putMaterialInfo
} from '../../../api/material'
import {dictData} from '../../../api/insure'

export default {
  data() {
    return {
      submitLoading: false,
      submitResetLoading: false,
      submitAddPutLoading: false,
      loading: false,
      detailDisabled: true,
      form: {},
      detailForm: {},
      formValidate: {},
      editDetailForm: {},
      editDetailFormValidate: {
        title: [{required: true, message: '不能为空', trigger: 'blur', type: 'string'}],
        amount: [{required: true, message: '数量不能为空', trigger: 'blur'}],
        unit: [
          {
            required: true,
            message: '单位不能为空',
            trigger: 'chanage',
            type: 'number'
          }
        ],
        price: [{required: true, message: '单价不能为空', trigger: 'blur'}]
      },
      detailFormValidate: {
        title: [{required: true, message: '不能为空', trigger: 'blur', type: 'string'}],
        amount: [{required: true, message: '数量不能为空', trigger: 'blur'}],
        unit: [
          {
            required: true,
            message: '单位不能为空',
            trigger: 'chanage',
            type: 'number'
          }
        ],
        price: [{required: true, message: '单价不能为空', trigger: 'blur'}]
      },
      openErrorAlert: false,
      columns: [
        {
          type: 'selection',
          width: 60,
          align: 'center',
          fixed: 'left'
        },
        {
          type: 'index',
          width: 60,
          align: 'center',
          fixed: 'left'
        },
        {
          title: '物资名称',
          key: 'title',
          width: 150,
          align: 'left'
        },
        {
          title: '规格',
          key: 'specs',
          align: 'center'
        },
        {
          title: '单位',
          key: 'unit_title',
          align: 'center'
        },
        {
          title: '数量',
          key: 'amount',
          align: 'center'
        },
        {
          title: '单价',
          key: 'price',
          align: 'right'
        },
        {
          title: '总价',
          key: 'total_price',
          align: 'right'
        },
        {
          title: '创建时间',
          key: 'created_at',
          align: 'right'
        },
        {
          title: '操作',
          slot: 'action',
          width: 120,
          fixed: 'right',
          align: 'center'
        }
      ],
      dict: [],
      busListData: [],
      index: 0,
      dataStart: [],
      modal: false,
      editModal: false,
      detailList: [],
      total: 2,
      selectCount: 0, // 多选计数
      selectList: [], // 多选数据
      process: {
        reason: ''
      },
      materialList: []
    }
  },
  watch: {
    $route: 'getPutMaterialInfo'
  },
  mounted() {
    this.getMaterialList()
    this.getPutMaterialInfo()
    this.getDictData()
  },
  methods: {
    addTitle(val) {
      const id_l = parseInt(this.materialList.length) + 100
      this.materialList.push({
        title: val,
        id: id_l
      })
    },
    cancel() {
      this.detailForm = {}
      this.editDetailForm = {}
    },
    del(row) {
      this.$Modal.confirm({
        title: '确认删除',
        loading: true,
        content: '您确认要删除此条数据吗？',
        onOk: () => {
          const ids = row.id
          // 批量删除
          editDelPutMaterialDetail(ids).then(res => {
            this.$Modal.remove()
            if (res.data === true) {
              this.$Message.success('保存成功')
              this.getPutMaterialInfo()
            } else {
              this.$Message.error('保存失败')
            }
          })
        }
      })
    },
    delAll() {
      if (this.selectCount <= 0) {
        this.$Message.warning('您还未选择要删除的数据')
        return
      }
      this.$Modal.confirm({
        title: '确认删除',
        loading: true,
        content: '您确认要删除所选的 ' + this.selectCount + ' 条数据？',
        onOk: () => {
          let ids = ''
          this.selectList.forEach(function (e) {
            ids += e.id + ','
          })
          ids = ids.substring(0, ids.length - 1)
          // 批量删除
          editDelPutMaterialDetail(ids).then(res => {
            this.$Modal.remove()
            if (res.data === true) {
              this.$Message.success('保存成功')
              this.getPutMaterialInfo()
            } else {
              this.$Message.error('保存失败')
            }
          })
        }
      })
    },
    edit(e) {
      this.editDetailForm = e
      this.editModal = true
    }, //修改详情
    editSubmitF() {
      if (this.editDetailForm.amount > 0) {
        this.$refs.editDetailForm.validate(valid => {
          if (valid) {
            this.submitAddPutLoading = true
            editMaterialDetail(this.editDetailForm).then(res => {
              this.submitAddPutLoading = false
              if (res.data) {
                this.getPutMaterialInfo()
              } else {
                this.$Message.error('保存失败')
              }
            })
            this.cancel()
            this.editModal = false
          }
        })
      } else {
        this.$Message.error('物资数量不能小于1')
      }
    },
    getDictData() {
      dictData({title: '物资单位'}).then(res => {
        if (res.data.result) {
          this.dict = res.data.result
        }
      })
    },
    getMaterialList() {
      materialListSelect({type: 'add'}).then(res => {
        this.materialList = res.data.personnel
      })
    },
    getPutMaterialInfo() {
      if (this.$route.params.id) {
        this.loading = true
        putMaterialInfo({id: this.$route.params.id}).then(res => {
          this.loading = false
          this.form.put_time = res.data.result.put_time
          this.form.supplier = res.data.result.supplier
          this.detailList = this.dataStart = res.data.result.detailList
          // if (res.data.result.supplier) {
          //   this.detailDisabled = false;
          // }
          this.process = res.data.result.process
          this.openErrorAlert =
            this.process.reason !== '' && this.process.status === 4
          let total_money = 0
          for (const i in this.detailList) {
            total_money =
              parseFloat(total_money) +
              parseFloat(this.detailList[i].total_price)
          }
          this.form.total_money = total_money.toFixed(2)
        })
      }
    },
    handleReset() {
      this.$refs.form.resetFields()
      this.form = {}
    },
    handleSubmit(name) {
      this.$refs.form.validate(valid => {
        if (valid) {
          this.form.detailList = this.detailList
          this.form.id = this.$route.params.id
          this.submitLoading = true
          editMaterial(this.form).then(res => {
            this.submitLoading = false
            if (res.data) {
              this.$Message.success('保存成功')
              this.$store.commit('closeTag', 'editPutMaterial')
              this.$router.push({
                name: 'putMaterial'
              })
            } else {
              this.$Message.error('保存失败')
            }
          })
        }
      })
    },
    handleSubmitReset() {
      this.$refs.form.validate(valid => {
        if (valid) {
          this.form.detailList = this.detailList
          this.form.id = this.$route.params.id
          this.form.status = 2
          this.submitResetLoading = true
          editMaterial(this.form).then(res => {
            this.submitResetLoading = false
            if (res.data) {
              this.$Message.success('保存成功')
              this.$store.commit('closeTag', 'editPutMaterial')
              this.$router.push({
                name: 'putMaterial'
              })
            } else {
              this.$Message.error('保存失败')
            }
          })
        }
      })
    },
    showSelect(e) {
      this.selectList = e
      this.selectCount = e.length
    },
    submitF() {
      if (this.detailForm.amount > 0) {
        this.$refs.detailForm.validate(valid => {
          if (valid) {
            this.detailForm.index = this.detailList.length
            this.detailForm.put_id = this.$route.params.id
            this.detailForm.supplier = this.form.supplier
            this.submitAddPutLoading = true
            editAddPutMaterialDetail(this.detailForm).then(res => {
              this.submitAddPutLoading = false
              if (res.data) {
                this.getPutMaterialInfo()
              } else {
                this.$Message.error('没有数据')
              }
            })
            // this.dataStart=this.detailList;
            this.modal = false
            this.cancel()
          }
        })
      } else {
        this.$Message.error('物资数量不能小于1')
      }
    },
    supplierChange() {
      if (this.form.supplier) {
        this.detailDisabled = false
      }
    },
    toAdd() {
      this.modal = true
    },//选择物资时触发
    changeMaterial(v) {
      const _this = this
      this.materialList.forEach(function (e) {
        if (v === e.title) {
          _this.detailForm.specs = e.specs
          _this.detailForm.unit = e.unit
          _this.detailForm.amount = e.amount
          _this.detailForm.price = e.price
        }
      })
    }, clearMaterial() {
      this.detailForm = {
        specs: '',
        unit: '',
        amount: '',
        price: null
      }
    },//选择物资时触发
    changeEditMaterial(v) {
      const _this = this
      this.materialList.forEach(function (e) {
        if (v === e.title) {
          _this.editDetailForm.specs = e.specs
          _this.editDetailForm.unit = e.unit
          _this.editDetailForm.price = e.price
        }
      })
    }, clearEditMaterial() {
      this.editDetailForm = {
        specs: '',
        unit: '',
        amount: '',
        price: null
      }
    }
  }
}
</script>
<style>
.ivu-row .ivu-col .ivu-form-item {
  width: 100%;
}
</style>
